package com.blb.mvc;

import com.blb.mvc.entity.Book;
import com.blb.mvc.entity.ResponseResult;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Restful风格的控制器
 */
@RestController
public class BookController {

    private List<Book> books = new ArrayList<>();

    {
        books.add(new Book(1L,"三国演义","罗贯中",44.4,"xx.jpg"));
        books.add(new Book(2L,"水浒传","施耐庵",44.4,"xx.jpg"));
        books.add(new Book(3L,"西游记","吴承恩",44.4,"xx.jpg"));
    }

    /**
     * 查询所有书籍
     */
    @GetMapping("/books")
    public ResponseResult findAll(){
        return ResponseResult.ok(books);
    }

    /**
     * 查询单个书籍
     */
    @GetMapping("/book/{id}")
    public ResponseResult findById(@PathVariable Long id){
        Book book1 = books.stream()
                .filter(book -> book.getId().equals(id))
                .collect(Collectors.toList()).get(0);
        return ResponseResult.ok(book1);
    }

    /**
     * 添加书籍
     * @param book
     * @return
     */
    @PostMapping("/book")
    public ResponseResult saveBook(@RequestBody Book book){
        books.add(book);
        return ResponseResult.ok("添加成功");
    }

    /**
     * 更新书籍
     * @param book
     * @return
     */
    @PutMapping("/book")
    public ResponseResult updateBook(@RequestBody Book book){
        //通过id查找到的书籍
        Book book1 = books.stream()
                .filter(book2 -> book2.getId().equals(book.getId()))
                .collect(Collectors.toList()).get(0);
        //将新书籍信息赋值给查找到的书籍
        BeanUtils.copyProperties(book,book1);
        return ResponseResult.ok("更新成功");
    }

    /**
     * 删除单个书籍
     */
    @DeleteMapping("/book/{id}")
    public ResponseResult deleteById(@PathVariable Long id){
        for(int i = 0;i < books.size();i++){
            if(books.get(i).getId().equals(id)){
                books.remove(i);
                break;
            }
        }
        return ResponseResult.ok("删除成功");
    }
}
